package com.swust.dumpling.web.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 					---------filter生命周期--------
 * 1>	在应用启动的时候就进行装载Filter类(与Servlet的load-on-startup配置效果相同).
 * 
 * 2>	容器创建好Filter对象实例后，调用init()方法,接着被Web容器保存进应用级的集合容器中去了等待着,用户访问资源.
 * 
 * 3>	当用户访问的资源正好被Filter的url-pattern拦截时,
 *   	容器会取出Filter类调用doFilter方法,
 *   	下次或多次访问被拦截的资源时,
 *   	Web容器会直接取出指定Filter对象实例调用doFilter方法(Filter对象常驻留Web容器了).
 *   
 * 4>	当应用服务被停止或重新装载了,则会执行Filter的destroy方法,Filter对象销毁.
 * 
 * 	attention：init方法与destroy方法只会直接一次。
 * */

public class PrepareAndExecuteFilter implements Filter {
	
	public static String CURRENT_PATH = "filter.PrepareAndExecuteFilter";

	//当服务器终结时,销毁该filter对象
	public void destroy() {
		
		System.out.println("\ncurrent path is : " + CURRENT_PATH);
		
		System.out.println("destroy ... ");
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		
		System.out.println("\ncurrent path is : " + CURRENT_PATH);
		
		//请求来临时访问doFilter.一个请求对应一次doFilter
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		if (request != null) {
			System.out.println("session id is \t: " + request.getSession().getId());
			System.out.println("contextPath is \t: " + request.getContextPath());
			System.out.println("url request is \t: " + request.getRequestURL());
			System.out.println("uri request is \t: " + request.getRequestURI());
			System.out.println("local address is \t: " + request.getLocalAddr() );
			System.out.println("local name is \t: " + request.getLocalName());
			System.out.println("request path info \t:" + request.getPathInfo());
			//url问号后面那个
			System.out.println("query String is \t: " + request.getQueryString());
			Enumeration<String> headers = request.getHeaderNames();
			//-------------------\\
			System.out.println("*************************");
			String str = null;
			while (headers.hasMoreElements()) {
				str = headers.nextElement();
				System.out.println(str + " \t: " + request.getHeader(str));
			}
			System.out.println("*************************");
		}
		System.out.println(chain);
		if ((response != null)) {
			response.sendError(404, "页面错误!");
		}
		
	}

	//最初的时光创建该filter
	public void init(FilterConfig arg0) throws ServletException {

		System.out.println("\ncurrent path is : " + CURRENT_PATH);
		
		System.out.println("init ...");
		
	}

}
